package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.constants.mq.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 文章自动审核方法
     * @param wmNewsId  自媒体文章id
     */
    @Override
    public void autoScanWmNews(Integer wmNewsId) {
        log.info(" 自动审核发布方法 被调用   当前审核发布的文章id==> {}",wmNewsId);
        //根据文章id 远程调用feign查询文章
        if (wmNewsId == null) {
            log.error("自动审核文章失败    文章id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        if (wmNews==null) {
            log.error("自动审核文章失败    未查询自媒体文章信息  wmNewsId:{}",wmNewsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //检查文章状态
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())){
            log.info("文章状态不为1,无需审核");
            return;
        }
        //抽取文章内容和图片
        Map<String,Object> contentAndImageResult = handleTextAndImages(wmNews);
        //DFA敏感词审核  不通过 修改状态为2
        boolean scanSensivice = handleSensitive((String)contentAndImageResult.get("content"),wmNews);
        if (!scanSensivice)return;
        //阿里云审核文章  不通过 修改状态为2  不确定 修改状态为3
        boolean isTextScan = handleTextScan((String)contentAndImageResult.get("content"),wmNews);
        if(!isTextScan) return;
        //阿里云审核图片  不通过 修改状态为2  不确定 修改状态为3
        //先判断图片是否为空
        List<String> images = (List<String>) contentAndImageResult.get("images");
        if (CollectionUtils.isEmpty(images)){
            //有图,判断
            boolean isImageScan =handleImageScan((List<String>)images,wmNews);
            if(!isImageScan) return;
        }
        //全部通过修改状态为 8
        updateWmNews(wmNews,(short)8,"审核通过");


        //文章发布功能发送消息,通知发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        if(remainTime <= 0){
            // 立即发布
            rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                    ,PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                    ,wmNews.getId()
            );
            log.info("立即发布文章通知成功发送，文章id : {}",wmNews.getId());
        }else {
            // 延时发布
            rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_DEAD_ROUTE_KEY
                    , wmNews.getId()
                    , (message)-> {
                        message.getMessageProperties().setExpiration(String.valueOf(remainTime));
                        return message;
                    }
            );
            log.info("延时发布文章通知成功发送，文章id : {} , 延时时间: {}毫秒",wmNews.getId(),remainTime);
        }
    }
    @Autowired
    GreenImageScan greenImageScan;
    /**
     * 阿里云审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        //调用文本审核的方法
        try {
            Map map = greenImageScan.imageUrlScan(images);
            //获取审核结果  PASS  REVIEW  BLOCK
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "review":
                    updateWmNews(wmNews,(short)2,"图片中有违规内容，审核失败");
                    flag = false;
                    break;
                case "block":
                    updateWmNews(wmNews,(short)3,"图片中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //审核失败  转人工审核
            log.error("阿里云图片审核出现异常 , 原因:{}",e.getMessage());
            updateWmNews(wmNews,(short)3,"阿里云内容服务异常，转为人工审核");
            flag = false;
        }
        return flag;
    }

    @Autowired
    GreenTextScan greenTextScan;
    /**
     * 阿里云审核文章
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        //调用文本审核的方法
        try {
            Map map = greenTextScan.greenTextScan(content);
            //获取审核结果  PASS  REVIEW  BLOCK
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "review":
                    updateWmNews(wmNews,(short)2,"文本中有违规内容，审核失败");
                    flag = false;
                    break;
                case "block":
                    updateWmNews(wmNews,(short)3,"文本中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //审核失败  转人工审核
            log.error("阿里云文本审核出现异常 , 原因:{}",e.getMessage());
            updateWmNews(wmNews,(short)3,"阿里云内容服务异常，转为人工审核");
            flag = false;
        }
        return flag;
    }

    @Autowired
    AdminFeign adminFeign;
    /**
     * DFA敏感词审核
     * @param content 待检测内容
     * @param wmNews  文章
     * @return  返回结果  true:审核通过  false:审核失败
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        //通过feign查询敏感词
        ResponseResult<List<String>> allSensitivesResult = adminFeign.selectAllChannel();
        if(allSensitivesResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        //获取敏感词列表
        List<String> data = allSensitivesResult.getData();
        //转化为DFA敏感词模型
        SensitiveWordUtil.initMap(data);
        //检测敏感词
        Map<String, Integer> senstiveMap = SensitiveWordUtil.matchWords(content);
        //判断是否通过
        if (senstiveMap!=null&&senstiveMap.size()>0){
            //没通过,修改状态
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"内容中包含敏感词: " + senstiveMap);
            flag = false;
            log.info("文章审核未通过   文章id:{}   未通过原因:包涵敏感词{}",wmNews.getId(),senstiveMap);
        }
        return flag;
    }

    /**
     * 抽取文章内容和图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        Map result = new HashMap();
        //获取文章中的图文信息content
        String contentJson = wmNews.getContent();
        //判断图文信息
        if (contentJson==null){
            log.error("自动审核文章失败    文章内容为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容为空");
        }
        //将contentJson转化为集合
        List<Map> contentMapList = JSONArray.parseArray(contentJson, Map.class);
        //拼接文本信息
        String content = contentMapList.stream().filter(map -> "text".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.joining("_hmtt_"));
        //拼接标题
        content+="_hmtt_"+wmNews.getTitle();
        //抽取文本内容
        result.put("content",content);

        //抽取图片信息
        //抽取文章中图片信息
        List<String> imageList = contentMapList.stream().filter(map -> "image".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.toList());
        //抽取封面中图片信息
        String images = wmNews.getImages();
        if (StringUtils.isNotBlank(images)){
            List<String> collect = Arrays.stream(images.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            imageList.addAll(collect);
        }
        //去重
        imageList = imageList.stream().distinct().collect(Collectors.toList());
        result.put("images",imageList);
        return result;
    }
    /**
     * 修改文章状态
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }
}
